
#include <BMesh>
#include <BGeometry>
#include <BBillboard>
#include <BTerrain>
#include <BSurface>
#include <BParticle>
#include <BTextual>
#include "SetupOriginOpera.h"

SetupOriginOpera::SetupOriginOpera(Target* target)
{
	_target = target;
	if (_target)
	{
		if (BShape* shape = _target->shape())
		{
			_oldOrigin = shape->position();
			_shape = shape;
			return;
		}
		if (BNode* node = _target->node())
		{
			_oldOrigin = node->position();
			_node = node;
			return;
		}
		if (BGroup* group = _target->group())
		{
			_oldOrigin = group->space().center();
			_group = group;
			return;
		}
	}
}
SetupOriginOpera::~SetupOriginOpera()
{

}

bool SetupOriginOpera::redo()
{
	if (_shape)
	{
		_shape->setPosition(_newOrigin);
		BMatrix matrix = _shape->matrix().inverse();
		BVector offset = _oldOrigin * matrix - _newOrigin * matrix;
		if (BMesh* mesh = _shape.as<BMesh>())
		{
			BVectorArray* vertices = mesh->vertices();
			for (int i = 0; i < vertices->size(); i++)
			{
				(*vertices)[i] += offset;
			}
			mesh->dirty();
		}
		if (BGeometry* geometry = _shape.as<BGeometry>())
		{
			BVectorArray* vertices = geometry->vertices();
			for (int i = 0; i < vertices->size(); i++)
			{
				(*vertices)[i] += offset;
			}
			geometry->dirty();
		}
		emit("target-changed", _target);
		return true;
	}
	if (_node)
	{
		_node->setPosition(_newOrigin);
		BMatrix matrix = _node->matrix().inverse();
		BVector offset = _oldOrigin * matrix - _newOrigin * matrix;
		for (int i = 0; i < _node->shapeCount(); i++)
		{
			BShape* shape = _node->shape(i);
			shape->move(offset);
		}
		emit("target-changed", _target);
		return true;
	}
	return false;
}
bool SetupOriginOpera::undo()
{
	if (_node)
	{
		_node->setPosition(_oldOrigin);
		BMatrix matrix = _node->matrix().inverse();
		BVector offset = _newOrigin * matrix - _oldOrigin * matrix;
		for (int i = 0; i < _node->shapeCount(); i++)
		{
			BShape* shape = _node->shape(i);
			shape->move(offset);
		}
		emit("target-changed", _target);
		return true;
	}
	return false;
}

void SetupOriginOpera::setOrigin(const BVector& origin)
{
	_newOrigin = origin;
}

